<?php
declare (strict_types = 1);

namespace app\api\http\middleware;

use thans\jwt\facade\JWTAuth;
use think\facade\Request;
use think\facade\Cache;
//use \think\Request;
use app\api\logic\AuthLogic;
use app\api\model\AdminUser;
class Auth
{

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $path = $request->pathinfo();
        $ex_path = explode("/",$path);
        $token = Cache::get('token');

        if(strtolower($ex_path[0]) == 'login'){
            return $next($request);
        }else{
            if($token){
                try {
                    $payload = JWTAuth::auth();
                    $username = $payload['username']->getValue();
                    $request->token_user_name = $username;

                }catch (\Exception $e){
                    return renderError($e->getMessage(),'',-1);
                }

            }else{
                return renderError('token已过期','',-1);
            }
        }
        //权限验证


        $user = AdminUser::where('username',$username)->find();
        if($user['is_super'] != 1){

            /*获取去重后的权限*/
            $access = AuthLogic::getMenus($user['id']);
            foreach ($access as $k=>$v){
                $path_access[]=strtolower($v['path']);
            }
            /*白名单*/
            $whiteList = ['/auth/getaccesslist'];
            $path_access = array_merge($whiteList,$path_access);
            /*获取当前控制器和方法*/
            $path = strtolower('/'.$path);
            if(!in_array($path,$path_access)){
                return renderError('您没有此操作权限');
            }

        }

        return $next($request);
    }
}
